<template>
  <div class="tree-container">
    <div class="header">
      <!-- <div class="title">组织机构管理</div> -->
      <div class="left">
        <el-input placeholder="请输入组织机构" v-model="orgName" style="width: 100%" size="small" clearable @clear="onClear">
          <el-button slot="append" :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'" @click="searchClick">
          </el-button>
        </el-input>
      </div>
    </div>
    <div :class="['middle', first ? 'middle1' : '']">
      <!--   :load="loadNode"
        lazy -->
      <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" v-if="isTree" node-key="id"
        default-expand-all ref="refTree" highlight-current :expand-on-click-node="false"
        :current-node-key="defaultCheckedKeys">
        <div class="custom-tree-node" slot-scope="{ node, data }" @mouseenter="slideIn(data)"
          @mouseleave="slideAway(data)">
          <div>
            <i class="iconfont jigouguanli" v-if="data.type == '1'"></i>
            <i class="iconfont zuzhi" v-else-if="data.type == '2'"></i>
            <i class="iconfont ditu2" v-else-if="data.type == '3'"></i>
            <i class="iconfont icon_unit" v-else-if="data.type == '4'"></i>
            {{ node.label }}
          </div>
        </div>
      </el-tree>
      <!-- <div @click="onclick">111</div> -->
    </div>

  </div>
</template>

<script>
import { reqOrgList, reqOrgDel, reqOrgExit } from "@api/api.js";
import { mapState } from "vuex";
import { handleTree, transTree } from "@utils/trans-tree";

export default {
  components: {},
  props: [""],
  mixins: [],
  data() {
    return {
      isTree: true,
      dataTree: [],
      page: 1,
      limit: 30,
      total: 0,
      orgName: "",
      defaultProps: {
        children: "children",
        label: "orgName",
        isLeaf: "hasChildren",
        id: "id",
      },
      first: true, //第一次加载，点击后消除
      loadingSearch: false,
      firstInfo: {}, //默认第一条信息
      editOrgInfo: {}, //修改一条组织机构信息
      detailOrgInfo: {}, //详情
      flagtree: false,
      data: [],
      parentId: "",
      currentData: "",
      currentNode: "",
      defaultCheckedKeys: "", // 选择节点后默认展示
      defaultCheckedKeys_copy: "",

      initOrgList: [],
      editId: ""
    };
  },
  computed: {
    ...mapState(["user", "spacesManage"]),
  },
  mounted() {
    // this.getDataList();
  },
  methods: {
    //点击复选框
    handleCheckChange(data, checkedList) {
      console.log(data, checkedList);
      this.$refs.refTree.setCurrentKey(data.id);
      this.$refs.refTree.setCheckedKeys([data.id]);
      let params = {
        orgId: data.id,
        orgName: data.orgName,
        role: data.role,
        type: data.type,
        parentId: data.parentId,
        parentName: data.parentName,
      };
      this.$emit("toggleOrgId", params);
    },
    async getInfo(id) {
      // this.editId=id;
      this.first = false;
      await this.getDataList(id);
      this.$nextTick(() => {
        this.$refs.refTree.setCurrentKey(id);//默认选中
        this.$refs.refTree.setCheckedKeys([id]);//默认选中
      })
    },
    // onclick(){
    //   this.defaultCheckedKeys =this.editId
    //   this.$nextTick(()=>{
    //     this.$refs.refTree.setCurrentKey('1900026348439650306');
    //     this.$refs.refTree.setCheckedKeys(['1900026348439650306']);
    //   })
    // },
    // 获取列表
    async getDataList(id) {
      let params = {
        tenantId: this.user.tenantId,
        userId: this.user.userId,
        roleName: this.user.roleName,
        orgName: this.orgName,
        parentId: "",
        type: "1,2,3"
      };
      let res = await reqOrgList(params);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let { rows, total } = res.data;
      this.data = transTree(rows);//返回全部数据
      if (id) {
        // 编辑
        rows.forEach(item => {
          if (item.id == id) {
            let data = {
              orgId: item.id,
              orgName: item.orgName,
              role: item.role,
              type: item.type,
              parentId: item.parentId,
              parentName: item.parentName,
            };
            this.$emit("toggleOrgId", data);
          }
        })
        return;
      }
      let data = {
        orgId: this.data[0].id,
        orgName: this.data[0].orgName,
        role: this.data[0].role,
        type: this.data[0].type,
        parentId: this.data[0].parentId,
        parentName: this.data[0].parentName,
      };
      this.$emit("toggleOrgId", data);
      // this.defaultCheckedKeys =this.editId
      // this.$refs.refTree.setCurrentKey(this.editId);
      // rows.forEach((item) => {
      //   if (item.hasChildren === 1) {
      //     item.hasChildren = false;
      //   } else {
      //     item.hasChildren = true;
      //   }
      // });
      // this.data = rows;
    },
    onDropdown(e, data) {
      switch (e) {
        case "delClick":
          this.$confirm(
            `此操作将永久删除组织机构${data.orgName}, 是否继续?`,
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(async () => {
              let res = await reqOrgDel(data.id);
              if (res.code !== 20000)
                return this.$modal.notifyWarning(res.message);
              this.$modal.notifySuccess("删除成功");
              this.$refs.refTree.remove(this.currentData); // 通过节点id找到对应树节点对象
            })
            .catch(() => { });
          break;
        case "editClick":
          this.$refs.refEdit.dialogVisible = true;
          this.editOrgInfo = JSON.parse(JSON.stringify(data));
          console.log(this.editOrgInfo, "this.editOrgInfo");
          this.$refs.refEdit.RegionList();
          this.$refs.refEdit.cityArr();
          this.$refs.refEdit.areaArr();
          this.$refs.refEdit.RegionLevelList();
          this.$refs.refEdit.communitylList();
          break;
        case "addNewSubUnit":
          this.parentId = data.id;
          this.$refs.refAdd.dialogVisible = true;
          break;
      }
    },
    // 树节点懒加载
    async loadNode(node, resolve) {
      if (node.level == 0) {
        // 如果是一级单位
        let params = {
          tenantId: this.user.tenantId,
          userId: this.user.userId,
          roleName: this.user.roleName,
          orgName: this.orgName,
          parentId: "",
          orgId: this.spacesManage.organizationInfo.orgId,
          type: "1,2,3"
        };
        let res = await reqOrgList(params);
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        let { rows, total } = res.data;
        rows.forEach((item) => {
          if (item.hasChildren === 1) {
            item.hasChildren = false;
          } else {
            item.hasChildren = true;
          }
        });
        if (!this.defaultCheckedKeys_copy) {
          if (rows.length > 0) {
            let data = {
              orgId: rows[0].id,
              orgName: rows[0].orgName,
              role: rows[0].role,
              isQuitOrg: true,
            };
            this.$emit("toggleOrgId", data);
          } else {
            // 组织机构筛选为空时
            let data = {
              orgId: "",
              orgName: "",
              role: 2,
            };
            this.$emit("toggleOrgId", data);
          }
        }
        if (!this.orgName) {
          this.initOrgList = rows;
        }
        return resolve(rows);
      } else {
        // 否则是下级单位
        let params = {
          tenantId: this.user.tenantId,
          userId: this.user.userId,
          roleName: this.user.roleName,
          // orgName: this.orgName,
          orgName: "",
          parentId: node.data.id,
          type: "1,2,3"
        };
        let res = await reqOrgList(params);
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        let rows = res.data.rows;
        rows.forEach((item) => {
          if (item.hasChildren === 1) {
            item.hasChildren = false;
          } else {
            item.hasChildren = true;
          }
        });
        return resolve(rows);
      }
    },
    // 更新整个单位
    updateOrg() {
      this.isTree = false;
      setTimeout(() => {
        this.isTree = true;
      }, 0);
      this.getInitDataList()
    },
    getInitDataList() {
      this.page = 1;
      this.limit = 30;
      this.getDataList();
    },
    // 点击新增一级组织机构
    addClick() {
      this.$refs.refAdd.dialogVisible = true;
      this.$refs.refAdd.closeDialog2(); //防止出现表单验证
      this.$refs.refAdd.RegionList();
    },
    // 点击一条
    handleNodeClick(data, node) {
      this.currentData = data;
      this.currentNode = node;
      this.$refs.refTree.setCurrentKey(data.id);
      this.defaultCheckedKeys = data.id;
      let isQuitOrg = false;
      if (this.initOrgList.length && this.initOrgList.length > 1) {
        for (let i = 0; i < this.initOrgList.length; i++) {
          if (this.initOrgList[i].id == data.id) {
            isQuitOrg = true;
            return;
          }
        }
      } else if (this.initOrgList.length && this.initOrgList.length == 1) {
        isQuitOrg = this.initOrgList[0].id == data.id ? true : false;
      }
      let params = {
        orgId: data.id,
        orgName: data.orgName,
        role: data.role,
        isQuitOrg,
        type: data.type,
        parentId: data.parentId,
        parentName: data.parentName,
      };
      this.$emit("toggleOrgId", params);
      this.first = false;
    },
    // 清空输入框
    async onClear() {
      if (this.defaultCheckedKeys_copy && !this.defaultCheckedKeys) {
        this.defaultCheckedKeys = this.defaultCheckedKeys_copy;
      }
      this.loadingSearch = true;
      await this.updateOrg();
      this.loadingSearch = false;
      this.first = true;
    },
    // 查询组织机构
    async searchClick() {
      this.loadingSearch = true;
      this.defaultCheckedKeys_copy = JSON.parse(
        JSON.stringify(this.defaultCheckedKeys)
      );
      await this.updateOrg();
      if (this.orgName != "") {
        this.defaultCheckedKeys = "";
      }
      this.loadingSearch = false;
      this.first = true;
    },
    // 滑动进去一条
    slideIn(data) {
      this.$set(data, "showCtrls", true);
    },
    slideAway(data) {
      // console.log(data);
      this.$set(data, "showCtrls", false);
    },
    // 点击编辑
    editClick(data) {
      this.$refs.refEdit.dialogVisible = true;
      this.editOrgInfo = JSON.parse(JSON.stringify(data));
      this.$refs.refEdit.RegionList();
      this.$refs.refEdit.cityArr();
      this.$refs.refEdit.areaArr();
      this.$refs.refEdit.RegionLevelList();
      this.$refs.refEdit.communitylList();
    },
    // 删除组织机构
    exit(data) {
      this.$confirm("此操作将退出该组织机构, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await reqOrgExit({
            orgId: data.id,
            userId: this.user.userId,
          });
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("退出组织机构成功!");
          this.getDataList();
        })
        .catch(() => { });
    },
    // 查看详情
    detailClick(data) {
      // console.log(data);
      this.$refs.refDetail.dialogVisible = true;
      this.detailOrgInfo = JSON.parse(JSON.stringify(data));
    },
    // 清除编辑数据
    clearEditOrgInfo() {
      this.editOrgInfo = {};
    },
    // 删除一个组织机构
    delClick(data) {
      this.$confirm(
        `此操作将永久删除组织机构${data.orgName}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          let res = await reqOrgDel(data.id);
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("删除成功");
          this.getInitDataList();
        })
        .catch(() => { });
    },
  },
};
</script>

<style scoped lang="less">
.tree-container {
  width: 100%;
  height: 100%;

  .header {
    position: relative;
    height: 65px;
    padding: 0 20px;
    border-bottom: 1px solid @primaryBorderColor;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .title {
      width: 25%;
      font-size: 20px;
      color: @primaryThemeTxtColor;
      font-weight: 600;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .el-icon-search {
      //   color: @primaryBorderColor;
      //   font-size: 20px;
    }

    .left {
      width: 100%;
    }

    .right {
      width: 75%;
      display: flex;
      justify-content: flex-end;
      //   justify-content: space-between;
    }
  }

  .middle {
    height: calc(100% - 65px);
    overflow: hidden;
    overflow-y: scroll;

    .custom-tree-node {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;
      padding-left: 0.5%;
      box-sizing: border-box;

      .guanliyuan_guanliyuanliebiao {
        position: absolute;
        left: -2.5%;
        font-size: 12px;
      }

      .tree-node_ctrls {
        position: absolute;
        right: 0;
        width: 30%;
        text-align: right;
        padding-right: 10px;
        // background-color: pink;

        i {
          color: #aaa;
          font-size: 20px;
          margin-right: 10px;

          &:hover {
            color: #fff;
          }
        }
      }
    }

    ::v-deep .el-tree {
      height: 100%;
      font-size: 14px;
      background: @primaryHeaderBgcolor;
      box-sizing: border-box;
      padding: 12px 10px;
      color: @primaryThemeTxtColor;
      overflow: hidden;
      overflow-y: scroll;
    }

    ::v-deep .el-tree-node__content {

      // padding: 5px 0 !important;
      &:hover {
        background: @paginationBgcolor !important;
        border-radius: 4px;
      }
    }

    ::v-deep .el-tree-node.is-current.is-focusable>.el-tree-node__content {
      background-color: #7367f0 !important;
      border-radius: 4px;
    }

    ::v-deep .el-tree-node.is-focusable>.el-tree-node__content {
      padding: 5px 0;
    }

    // 解决点击白底问题
    ::v-deep .el-tree-node.is-focusable>.el-tree-node__content {
      // background-color: @primaryTree;
      border-radius: 4px;
    }

    ::v-deep .is-current>.el-tree-node__content>.el-tree-node__label {
      color: #f0f0f0;
    }

    .el-icon-more {
      color: @primaryThemeTxtColor;
      font-size: 15px;
      margin-right: 10px;
    }

    // 组织机构更多
    ::v-deep .is-current>.el-tree-node__content>.custom-tree-node>.el-dropdown .el-icon-more {
      color: #f0f0f0;
    }
  }

  .middle1 {
    // ::v-deep .el-tree .el-tree-node.is-focusable:first-child {
    //   background-color: #7367f0 !important;
    //   border-radius: 4px;
    //   .el-tree-node__content {
    //     color: #f6f6f6;
    //   }

    //   .el-tree-node__content {
    //     padding: 5px 0 !important;
    //     &:hover {
    //       background: #7367f0 !important;
    //       border-radius: 4px;
    //     }
    //   }
    // }

    // 解决点击白底问题
    ::v-deep .el-tree>.el-tree-node:first-of-type>.el-tree-node__content {
      background-color: #7367f0 !important;
      color: #f0f0f0;
    }

    // 组织机构更多
    ::v-deep .el-tree>.el-tree-node:first-of-type>.el-tree-node__content .el-icon-more {
      color: #f0f0f0;
    }
  }
}

// 解决收起后白色背景问题
::v-deep .el-tree-node.is-expanded>.el-tree-node__content {
  background-color: transparent;
}

// 解决展开后白色背景问题
::v-deep .el-tree-node.is-focusable>.el-tree-node__content {
  background-color: transparent;
}

// input后面的查询按钮
::v-deep .el-input-group__append {
  color: #fff;
  border: none;
  background-color: #7367f0;
}

.gengduo2 {
  color: @primaryThemeTxtColor;
  font-size: 15px;
  margin-right: 8px;
}
</style>
